// 游戏状态管理
class HamsterGame {
    constructor() {
        this.hamster = null;
        this.isAdopted = false;
        this.lastUpdate = Date.now();
        this.init();
    }

    init() {
        this.loadGameData();
        this.setupEventListeners();
        this.updateDisplay();
        this.startGameLoop();
    }

    loadGameData() {
        const savedData = localStorage.getItem('hamsterGame');
        if (savedData) {
            const data = JSON.parse(savedData);
            this.hamster = data.hamster;
            this.isAdopted = data.isAdopted;
            this.lastUpdate = data.lastUpdate || Date.now();
        }
    }

    saveGameData() {
        const data = {
            hamster: this.hamster,
            isAdopted: this.isAdopted,
            lastUpdate: this.lastUpdate
        };
        localStorage.setItem('hamsterGame', JSON.stringify(data));
    }

    setupEventListeners() {
        // 导航切换
        document.querySelectorAll('.nav-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                this.switchPage(e.target.dataset.page);
            });
        });

        // 领养仓鼠
        document.querySelectorAll('.adopt-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const hamsterType = e.target.closest('.hamster-card').dataset.hamster;
                this.adoptHamster(hamsterType);
            });
        });

        // 宠物互动
        document.getElementById('feed-btn').addEventListener('click', () => this.feedHamster());
        document.getElementById('clean-btn').addEventListener('click', () => this.cleanHamster());
        document.getElementById('play-btn').addEventListener('click', () => this.playWithHamster());
        
        // 点击仓鼠互动
        document.getElementById('hamster-emoji').addEventListener('click', () => this.clickHamster());
        
        // 重命名
        document.getElementById('rename-btn').addEventListener('click', () => this.renameHamster());
    }

    switchPage(pageName) {
        // 更新导航按钮状态
        document.querySelectorAll('.nav-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        document.querySelector(`[data-page="${pageName}"]`).classList.add('active');

        // 切换页面显示
        document.querySelectorAll('.page').forEach(page => {
            page.classList.remove('active');
        });
        document.getElementById(`${pageName}-page`).classList.add('active');

        // 特殊处理
        if (pageName === 'leaderboard') {
            this.updateLeaderboard();
        }
    }

    adoptHamster(type) {
        const names = {
            golden: '小金',
            white: '小白',
            gray: '小灰'
        };

        this.hamster = {
            type: type,
            name: names[type],
            hunger: 80,
            clean: 75,
            mood: 90,
            adoptDate: Date.now(),
            interactions: 0
        };
        this.isAdopted = true;
        
        this.saveGameData();
        this.switchPage('pet');
        this.updateDisplay();
    }

    feedHamster() {
        if (!this.hamster) return;
        
        this.hamster.hunger = Math.min(100, this.hamster.hunger + 20);
        this.hamster.mood = Math.min(100, this.hamster.mood + 5);
        this.hamster.interactions++;
        
        this.saveGameData();
        this.updateDisplay();
        this.showActionFeedback('饱食度 +20！');
    }

    cleanHamster() {
        if (!this.hamster) return;
        
        this.hamster.clean = Math.min(100, this.hamster.clean + 25);
        this.hamster.mood = Math.min(100, this.hamster.mood + 10);
        this.hamster.interactions++;
        
        this.saveGameData();
        this.updateDisplay();
        this.showActionFeedback('清洁度 +25！');
    }

    playWithHamster() {
        if (!this.hamster) return;
        
        this.hamster.mood = Math.min(100, this.hamster.mood + 15);
        this.hamster.hunger = Math.max(0, this.hamster.hunger - 10);
        this.hamster.clean = Math.max(0, this.hamster.clean - 5);
        this.hamster.interactions++;
        
        this.saveGameData();
        this.updateDisplay();
        this.showActionFeedback('心情值 +15！');
    }

    clickHamster() {
        if (!this.hamster) return;
        
        // 随机心情变化
        const change = Math.random() > 0.5 ? 10 : -5;
        this.hamster.mood = Math.max(0, Math.min(100, this.hamster.mood + change));
        this.hamster.interactions++;
        
        // 显示不同的表情
        const emojis = {
            golden: ['🐹', '😊', '🥰', '🤗'],
            white: ['🐭', '😄', '😍', '🤭'],
            gray: ['🐁', '😆', '🥳', '🤩']
        };
        
        const emojiArray = emojis[this.hamster.type];
        const randomEmoji = emojiArray[Math.floor(Math.random() * emojiArray.length)];
        document.getElementById('hamster-emoji').textContent = randomEmoji;
        
        setTimeout(() => {
            document.getElementById('hamster-emoji').textContent = emojiArray[0];
        }, 1000);
        
        this.saveGameData();
        this.updateDisplay();
    }

    renameHamster() {
        if (!this.hamster) return;
        
        const newName = prompt('给你的仓鼠起个新名字吧！', this.hamster.name);
        if (newName && newName.trim()) {
            this.hamster.name = newName.trim();
            this.saveGameData();
            this.updateDisplay();
        }
    }

    updateDisplay() {
        if (!this.isAdopted) {
            document.getElementById('home-page').classList.add('active');
            return;
        }

        // 更新宠物页面
        document.getElementById('hamster-name').textContent = this.hamster.name;
        document.getElementById('hamster-emoji').textContent = this.getHamsterEmoji();
        
        // 更新状态条
        this.updateStatusBar('hunger', this.hamster.hunger);
        this.updateStatusBar('clean', this.hamster.clean);
        this.updateStatusBar('mood', this.hamster.mood);
        
        // 更新信息
        const days = Math.floor((Date.now() - this.hamster.adoptDate) / (1000 * 60 * 60 * 24)) + 1;
        document.getElementById('adopt-days').textContent = days;
        document.getElementById('interactions').textContent = this.hamster.interactions;
    }

    updateStatusBar(type, value) {
        const bar = document.getElementById(`${type}-bar`);
        const valueSpan = document.getElementById(`${type}-value`);
        
        if (bar && valueSpan) {
            bar.style.width = `${value}%`;
            valueSpan.textContent = `${value}%`;
            
            // 根据数值改变颜色
            if (value < 30) {
                bar.style.background = '#ff6b6b';
            } else if (value < 60) {
                bar.style.background = '#ffa726';
            } else {
                bar.style.background = 'linear-gradient(90deg, #667eea, #764ba2)';
            }
        }
    }

    getHamsterEmoji() {
        const emojis = {
            golden: '🐹',
            white: '🐭',
            gray: '🐁'
        };
        return emojis[this.hamster.type] || '🐹';
    }

    showActionFeedback(message) {
        const feedback = document.createElement('div');
        feedback.className = 'action-feedback';
        feedback.textContent = message;
        feedback.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(102, 126, 234, 0.9);
            color: white;
            padding: 15px 30px;
            border-radius: 25px;
            font-size: 18px;
            z-index: 1000;
            animation: fadeInOut 2s ease-in-out;
        `;
        
        document.body.appendChild(feedback);
        
        setTimeout(() => {
            feedback.remove();
        }, 2000);
    }

    updateLeaderboard() {
        // 模拟排行榜数据
        const leaderboard = [
            { name: '阳光', type: 'golden', score: 95, days: 15 },
            { name: '雪球', type: 'white', score: 92, days: 12 },
            { name: '烟灰', type: 'gray', score: 88, days: 10 },
            { name: '小灰', type: 'gray', score: 85, days: 8 },
            { name: '小白', type: 'white', score: 82, days: 5 }
        ];

        // 如果用户领养了仓鼠，添加到排行榜
        if (this.hamster) {
            const avgScore = Math.floor((this.hamster.hunger + this.hamster.clean + this.hamster.mood) / 3);
            const days = Math.floor((Date.now() - this.hamster.adoptDate) / (1000 * 60 * 60 * 24)) + 1;
            
            leaderboard.unshift({
                name: this.hamster.name,
                type: this.hamster.type,
                score: avgScore,
                days: days
            });
            
            // 按分数排序
            leaderboard.sort((a, b) => b.score - a.score);
        }

        const leaderboardList = document.getElementById('leaderboard-list');
        leaderboardList.innerHTML = '';

        leaderboard.slice(0, 5).forEach((item, index) => {
            const div = document.createElement('div');
            div.className = 'leaderboard-item';
            
            const emoji = {
                golden: '🐹',
                white: '🐭',
                gray: '🐁'
            };
            
            div.innerHTML = `
                <div class="rank">${index + 1}</div>
                <div class="leaderboard-emoji">${emoji[item.type]}</div>
                <div class="leaderboard-info">
                    <div class="leaderboard-name">${item.name}</div>
                    <div class="leaderboard-score">健康指数: ${item.score} | 领养天数: ${item.days}</div>
                </div>
            `;
            
            leaderboardList.appendChild(div);
        });
    }

    startGameLoop() {
        setInterval(() => {
            if (this.hamster) {
                // 自然衰减
                this.hamster.hunger = Math.max(0, this.hamster.hunger - 1);
                this.hamster.clean = Math.max(0, this.hamster.clean - 0.5);
                this.hamster.mood = Math.max(0, this.hamster.mood - 0.3);
                
                this.saveGameData();
                this.updateDisplay();
            }
        }, 60000); // 每分钟更新一次
    }
}

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
    @keyframes fadeInOut {
        0% { opacity: 0; transform: translate(-50%, -50%) scale(0.8); }
        50% { opacity: 1; transform: translate(-50%, -50%) scale(1); }
        100% { opacity: 0; transform: translate(-50%, -50%) scale(0.8); }
    }
`;
document.head.appendChild(style);

// 初始化游戏
const game = new HamsterGame();